﻿//by  张海军 710605420@qq.com
using UnityEngine;
using XLua;
using LazyFramework.LUA.UI;

namespace LazyFramework
{
    public class XluaManager : MonoSingleton<XluaManager>
    {
        public LuaTable globalMT = null;
//         public static XluaManager Instance { get { return Nested.instance; } }
// 
//         private class Nested
//         {
//             // Explicit static constructor to tell C# compiler
//             // not to mark type as beforefieldinit
//             static Nested()
//             {
//             }
//             internal static readonly XluaManager instance = new XluaManager();
//         }

        private LuaEnv luaEnv = null;
        private LuaFunction _createLuaUIFunc = null;

        public LuaFunction createLuaUIFunc
        {
            get
            {
                if(_createLuaUIFunc == null)
                {
                    _createLuaUIFunc = luaEnv.Global.GetInPath<LuaFunction>("xlua.CreateLuaUI");
                }
                return _createLuaUIFunc;
            }
        }

        // Use this for initialization
        //Must be Inited after the load is completed
        protected override void Init()
        {
            base.Init();
            luaEnv = new LuaEnv();
            if (luaEnv != null)
            {
                luaEnv.AddLoader(CustomLoader);
              
                LoadMain();

                globalMT = luaEnv.NewTable();
                globalMT.Set("__index", luaEnv.Global);
            }
        }

        // reload lua
        public void ReloadMain()
        {
            try
            {
                LuaUIManager.Instance.Clear();
                if (luaEnv != null)
                {
                    luaEnv.DoString("package.loaded['Main'] = nil");
                }
            }
            catch (System.Exception ex)
            {
                string msg = string.Format("xLua exception : {0}\n {1}", ex.Message, ex.StackTrace);
                Debug.LogError(msg, null);
            }
            LoadMain();
        }

        void LoadMain()
        {
            try
            {
                if (luaEnv != null)
                {
                    luaEnv.DoString("require('Main')");
                }
            }
            catch (System.Exception ex)
            {
                string msg = string.Format("xLua exception : {0}\n {1}", ex.Message, ex.StackTrace);
                Debug.LogError(msg, null);
            }
        }
        public static byte[] CustomLoader(ref string filepath)
        {
            Debug.Log("Load xLua script : " + filepath);
            // TODO：此处从项目资源管理器加载lua脚本
            TextAsset textAsset = (TextAsset)Resources.Load("Bundle/HotFixLua/" + filepath.Replace(".", "/") + ".lua");
            //TextAsset textAsset = (TextAsset)ResourceMgr.instance.SyncLoad(ResourceMgr.RESTYPE.XLUA_SCRIPT, filepath).resObject;
            if (textAsset != null)
            {
                Debug.Log("在此处对lua加解密，以及签名");
                return textAsset.bytes;
            }
            return null;
        }


        void Release()
        {
            if (globalMT != null)
                globalMT = null;
            if (luaEnv != null)
            {
                luaEnv.Dispose();
                luaEnv = null;
            }
        }
        public void LoadFixLua(string lua)
        {
            luaEnv.DoString(lua);
        }

        public void Update()
        {
            if (luaEnv != null)
                luaEnv.Tick();
            if (UnityEngine.Time.frameCount % 100 == 0)
            {
                luaEnv.FullGc();
            }
        }

    }

}
